/**
 *  *2010-10-1 下午10:11:33  add 
 */
package com.base.myproject.client.busi.payment;

import java.util.ArrayList;
import java.util.List;

import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.ColumnInfo;
import com.base.myproject.client.busi.Editdisable;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.tools.SendServlet;
import com.base.myproject.client.ui.GroupCheckBoxSelectionModel;
import com.base.myproject.client.ui.celleditor.BaseComboBoxForm;
import com.base.myproject.client.ui.celleditor.BaseSimpleCombox;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.BasePagingLoader;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.data.PagingLoadResult;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.store.GroupingStore;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.Window;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.Field;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.SimpleComboBox;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.form.FormPanel.LabelAlign;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridGroupRenderer;
import com.extjs.gxt.ui.client.widget.grid.GridViewConfig;
import com.extjs.gxt.ui.client.widget.grid.GroupColumnData;
import com.extjs.gxt.ui.client.widget.grid.GroupSummaryView;
import com.extjs.gxt.ui.client.widget.grid.SummaryColumnConfig;
import com.extjs.gxt.ui.client.widget.layout.TableData;
import com.extjs.gxt.ui.client.widget.layout.TableLayout;
import com.google.gwt.user.client.ui.Label;

/**
 * 收付款选择对话框，选择发票
 * 
 * @author Administrator 2010-10-1 javazgw@gmail.com
 */
public class PaymenItemDialog {
	final Window w = new Window();
	final Button yesbutton = new Button("确定");
	final Button button = new Button("取消");
	Button reloadbutton = new Button("刷新");
	boolean b;

	Grid<BusiObject> grid;
	BaseStore<BusiObject> basestore;
	BaseStore<BusiObject> target_store;
	ColumnInfo[] sourcecol;
	ColumnInfo[] target_col;
	TextField<String> barcode;
	TextField<String> cgcode;
	TextField<String> modeltype;
	SimpleComboBox gcode;
//	BaseStore<BusiObject> g_store = null;
//	BaseGrid g_grid = null;
	BasePagingLoader<PagingLoadResult<BusiObject>> loder;
	SendServlet ss = new SendServlet();
	ColumnModel cm;
	ModelType type ;
	StoreInfo info;
	int paytype ; //2 收款 1 付款
	public PaymenItemDialog(int paytype) {
		this.paytype = paytype;
		init();
	}

	private void init() {

		initWidget();
	}

	private void initWidget() {
		createGrid();
//		create_g_grid();
		yesbutton.addListener(Events.Select, getListener());
		button.addListener(Events.Select, getListener());
		reloadbutton.addListener(Events.Select, getListener());
		w.setHeading("发票选择");
		w.setModal(true);
		w.setSize(776, 500);
		w.setMaximizable(true);

		FormPanel panel = new FormPanel();

		panel.setFrame(true);

		// panel.setIcon(com.base.myproject.client.system.BaseResource.i.table());
		// panel.setIcon(Resources.ICONS.form());
		panel.setHeaderVisible(false);
		panel.setSize(750, -1);
		panel.setLabelAlign(LabelAlign.TOP);
		panel.setButtonAlign(HorizontalAlignment.CENTER);

		TableLayout tl = new TableLayout(4);
		TableData td = new TableData();
		td.setPadding(5);
		td.setColspan(1);
		td.setRowspan(1);
		panel.setLayout(tl);



		barcode = new TextField<String>();
		barcode.setFieldLabel("barcode");

		cgcode = new TextField<String>();
		// ComboBox cgcode = new ComboBox();
		// cgcode.setStore(basestore);
		cgcode.setFieldLabel("商品名称");

		modeltype = new TextField<String>();
		modeltype.setFieldLabel("规格型号");

		gcode = (SimpleComboBox) getFormInput("gcode");
		// TextField<String> gcode = new TextField<String>();
		gcode.setFieldLabel("类型");


		panel.add(new Label(barcode.getFieldLabel()), td);
		panel.add(barcode, td);
		panel.add(new Label(cgcode.getFieldLabel()), td);
		panel.add(cgcode, td);
		panel.add(new Label(modeltype.getFieldLabel()), td);
		panel.add(modeltype, td);
		panel.add(new Label(gcode.getFieldLabel()), td);
		panel.add(gcode, td);
		panel.setButtonAlign(HorizontalAlignment.CENTER);
		panel.addButton(reloadbutton);
		w.add(panel);
		VerticalPanel vpanel = new VerticalPanel();
		vpanel.add(grid);
//		vpanel.add(g_grid);
		w.add(vpanel);
		w.addButton(yesbutton);
		w.addButton(button);
	}

	GroupingStore<BusiObject>  store = null;

	GroupingStore<BusiObject>  getStore() {
		if (store == null) {
			createStore();
		}
		return store;
	}

	GroupingStore<BusiObject> createStore() {
		type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		type.addField("icode");
		type.getField("icode").setType(Long.class);
		type.addField("upicode");
		type.getField("upicode").setType(Long.class);
		type.addField("copybusicode");
		type.getField("copybusicode").setType(String.class);
		type.addField("copyicode");
		type.getField("copyicode").setType(String.class);
		type.addField("cgicode");
		type.getField("cgicode").setType(String.class);
		type.addField("cgcode");
		type.getField("cgcode").setType(String.class);
		type.addField("modeltype");
		type.getField("modeltype").setType(String.class);
		type.addField("gcode");
		type.getField("gcode").setType(String.class);
		type.addField("qty");
		type.getField("qty").setType(Double.class);
		type.addField("qtyunit");
		type.getField("qtyunit").setType(String.class);
		type.addField("qtp");
		type.getField("qtp").setType(Double.class);
		type.addField("qtpunit");
		type.getField("qtpunit").setType(String.class);
		type.addField("upric");
		type.getField("upric").setType(Double.class);
		type.addField("type");
		type.getField("type").setType(Long.class);
		 info = new StoreInfo();
		info.setTablename("null");
		info.setKeyname(new String[] { "icode" });
//		info.setSql("select * from invoice");
		// info.setParent(mainstore);// 关联主表
		// info.setLinkparentcolumns(new String[] { "icode" }); // 关联主表字段
		// info.setLinkparent_chile_columns(new String[] { "upicode" });//
		// 关联主表字段
		//store = new BaseStore<BusiObject>(type, info,false);
		loder = ss.getBaseLoaderX(type, info);
		store = new GroupingStore<BusiObject>(loder);
		store.groupBy("upicode");
		return store;
	}



	Grid createGrid() {
		GroupCheckBoxSelectionModel cbs = new GroupCheckBoxSelectionModel();
		List<ColumnConfig > columns = new ArrayList<ColumnConfig>();
		columns.add(cbs.getColumn());

		SummaryColumnConfig C4 = new SummaryColumnConfig("upicode", "发票号", 80);
		columns.add(C4);
		SummaryColumnConfig C5 = new SummaryColumnConfig("cgicode", "barcode", 80);
		columns.add(C5);
		SummaryColumnConfig C6 = new SummaryColumnConfig("cgcode", "商品名称", 80);
		columns.add(C6);
		SummaryColumnConfig C7 = new SummaryColumnConfig("modeltype", "商品规格", 80);
		columns.add(C7);
		SummaryColumnConfig C8 = new SummaryColumnConfig("gcode", "商品大类", 80);
		columns.add(C8);
		SummaryColumnConfig C9 = new SummaryColumnConfig("qty", "数量", 80);
		columns.add(C9);
		SummaryColumnConfig C10 = new SummaryColumnConfig("qtyunit", "单位", 80);
		columns.add(C10);
//		ColumnConfig C11 = new ColumnConfig("qtp", "qtp", 80);
//		columns.add(C11);
//		ColumnConfig C12 = new ColumnConfig("qtpunit", "qtpunit", 80);
//		columns.add(C12);
		SummaryColumnConfig C13 = new SummaryColumnConfig("upric", "单价", 80);
		columns.add(C13);
		
		cm = new ColumnModel(columns);
		
		
		GroupSummaryView view = new GroupSummaryView();
		//view.setShowGroupedColumn(false);
		view.setShowDirtyCells(false);
		view.setForceFit(true);
		view.setGroupRenderer(new GridGroupRenderer() {
			public String render(GroupColumnData data) {
				String f = cm.getColumnById(data.field).getHeader();
				String l = data.models.size() == 1 ? "条" : "条";
				return f + ": " + data.group + " (" + data.models.size() + " "
						+ l + ")";
			}
		});
		view.setShowGroupedColumn(true);
		
		
		grid = new Grid(getStore(), cm);
		
		GridViewConfig gvc = new GridViewConfig()
		{
			public String getRowStyle(ModelData model, int rowIndex, ListStore<ModelData> ds) {
			
				if(model.get("type").equals("-1"))
				{
					return "gridviewbackgroup";
				}
				return "";
			  }

		};
		view.setViewConfig(gvc);

		
		cbs.setSelectionMode(SelectionMode.MULTI);
		grid.addPlugin(cbs);
		grid.setView(view);
		grid.setLoadMask(true);
		grid.setSelectionModel(cbs);
		grid.setSize(760,280);
		return grid;
	}


/*
	BaseStore<BusiObject> get_g_store() {
		if (g_store == null) {
			create_g_store();
		}
		return g_store;
	}

	BaseStore<BusiObject> create_g_store() {
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		type.addField("icode");
		type.getField("icode").setType(Long.class);
		type.addField("upicode");
		type.getField("upicode").setType(Long.class);
		type.addField("copybusicode");
		type.getField("copybusicode").setType(String.class);
		type.addField("copyicode");
		type.getField("copyicode").setType(String.class);
		type.addField("cgicode");
		type.getField("cgicode").setType(String.class);
		type.addField("cgcode");
		type.getField("cgcode").setType(String.class);
		type.addField("modeltype");
		type.getField("modeltype").setType(String.class);
		type.addField("gcode");
		type.getField("gcode").setType(String.class);
		type.addField("qty");
		type.getField("qty").setType(Double.class);
		type.addField("qtyunit");
		type.getField("qtyunit").setType(String.class);
		type.addField("qtp");
		type.getField("qtp").setType(Double.class);
		type.addField("qtpunit");
		type.getField("qtpunit").setType(String.class);
		type.addField("upric");
		type.getField("upric").setType(Double.class);
		StoreInfo info = new StoreInfo();
		info.setTablename("null");
		info.setKeyname(new String[] { "icode" });
		info.setSql("select * from invoiceg where upicode ={icode}");
		 info.setParent(store);// 关联主表
		 info.setLinkparentcolumns(new String[] { "icode" }); // 关联主表字段
		 info.setLinkparent_chile_columns(new String[] { "upicode" });//
		// 关联主表字段
		g_store = new BaseStore<BusiObject>(type, info);
		return g_store;
	}*/

	

/*	BaseGrid create_g_grid() {
		CheckBoxSelectionModel cbs = new CheckBoxSelectionModel();
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		columns.add(cbs.getColumn());

//		ColumnConfig C1 = new ColumnConfig("icode", "icode", 80);
//		columns.add(C1);
//		ColumnConfig C2 = new ColumnConfig("upicode", "upicode", 80);
//		columns.add(C2);
//		ColumnConfig C3 = new ColumnConfig("copybusicode", "copybusicode", 80);
//		columns.add(C3);
//		ColumnConfig C4 = new ColumnConfig("copyicode", "copyicode", 80);
//		columns.add(C4);
		ColumnConfig C5 = new ColumnConfig("cgicode", "cgicode", 80);
		columns.add(C5);
		ColumnConfig C6 = new ColumnConfig("cgcode", "cgcode", 80);
		columns.add(C6);
		ColumnConfig C7 = new ColumnConfig("modeltype", "modeltype", 80);
		columns.add(C7);
		ColumnConfig C8 = new ColumnConfig("gcode", "gcode", 80);
		columns.add(C8);
		ColumnConfig C9 = new ColumnConfig("qty", "qty", 80);
		columns.add(C9);
		ColumnConfig C10 = new ColumnConfig("qtyunit", "qtyunit", 80);
		columns.add(C10);
		ColumnConfig C11 = new ColumnConfig("qtp", "qtp", 80);
		columns.add(C11);
		ColumnConfig C12 = new ColumnConfig("qtpunit", "qtpunit", 80);
		columns.add(C12);
		ColumnConfig C13 = new ColumnConfig("upric", "upric", 80);
		columns.add(C13);

		ColumnModel cm = new ColumnModel(columns);
		g_grid = new BaseGrid(get_g_store(), cm,false,false);
		cbs.setSelectionMode(SelectionMode.MULTI);
		g_grid.setSelectionModel(cbs);
		g_grid.addPlugin(cbs);
		g_grid.setSize(760,150);
		return g_grid;
	}*/
	private String getsql()
	{
		
		String str ="";
		str+="select upicode,busicode ,cgicode,cgcode,gcode,modeltype,upric,qty, qtyunit,type from       ";
		str+="( ";
		str+="select upicode,(select busicode from invoice where invoice.icode = invoiceg.upicode) as busicode,cgicode,cgcode,gcode,modeltype,upric,qty, qtyunit,1 as type from invoiceg ";
		str+=" where exists (select * from invoice where invoiceg.upicode = invoice.icode and invoice.invoicetype ="+paytype+")";
		str+="union all      ";
		str+="select copyicode,copybusicode,cgicode,cgcode,gcode,modeltype,upric,qty, qtyunit,-1 as type from paymentsg      ";
		str+=" where exists (select * from payments where paymentsg.upicode = payments.icode and payments.paytype ="+paytype+")";
		
		str+=") as z   ";
		str+="where exists   ";
		str+="   ";
		str+="(  ";
		str+="select * from (";
		str+="select upicode,sum(isnull(qty,0)*type) as lastqty,cgicode,cgcode,gcode,modeltype from  ";
		str+="(  ";
		str+="select upicode,(select busicode from invoice where invoice.icode = invoiceg.upicode) as busicode,cgicode,cgcode,gcode,modeltype,upric,qty, qtyunit,1 as type from invoiceg ";
		str+=" where exists (select * from invoice where invoiceg.upicode = invoice.icode and invoice.invoicetype ="+paytype+")";
		str+="union all      ";
		str+="select copyicode,copybusicode,cgicode,cgcode,gcode,modeltype,upric,qty, qtyunit,-1 as type from paymentsg      ";
		str+=" where exists (select * from payments where paymentsg.upicode = payments.icode and payments.paytype ="+paytype+")";
		str+=") as a   ";
		str+="group by upicode,cgicode,cgcode,gcode,modeltype    ";
		str+=") as b where z.upicode = b.upicode and b.lastqty>0 ";
		str+=") ";
		return str;
	}
public  void doposted(List<BusiObject> at) {
		
		
	}
	protected void close() {
		grid = null;
		basestore = null;

		sourcecol = null;
		target_col = null;

		
		barcode = null;
		cgcode = null;
		modeltype = null;
		gcode = null;
		w.hide();
		
	}       
	public Field getFormInput(String  name)
	{
		
		if(name.equals("scode"))
		{
			
	
		ModelType scodetype = new ModelType();
		scodetype.setRoot("records");
		scodetype.setRecordName("record");

		scodetype.addField("code");

		scodetype.addField("name");

		StoreInfo scodeinfo = new StoreInfo();
		scodeinfo.setForcenolimit("true");
		 scodeinfo.setTablename("ccode");
		 scodeinfo.setSql("select code,name from dictionary where type ='2'");
		BaseStore<BaseModelData> scodestore = new BaseStore<BaseModelData>(
				scodetype, scodeinfo);
		BaseComboBoxForm<BaseModelData> scode = new BaseComboBoxForm<BaseModelData>("code",
				"name", scodestore);
		scode.setFieldLabel("仓库");
		scode.setName("scode");
		
		return scode;
		}
		else if(name.equals("gcode")){
			BaseSimpleCombox bsc =new BaseSimpleCombox("gname","gcode","");
			
			return bsc.getCombox();
		}
		return null;
	}
	public void show()
	{
		
		if (!b) {
			
			w.show();
			b = true;
		} else
			w.show();
	}
	int sync = 0;                                                      
	Listener<BaseEvent> defaultlistener;                               
                                                                     
	Listener<BaseEvent> getListener() {                                
		if(defaultlistener!=null)                                        
		{                                                                
			return defaultlistener;                                        
		}                                                                
                                                                     
		defaultlistener = new Listener<BaseEvent>() {                    
			public void handleEvent(BaseEvent be) {                        
				sync++;                                                      
				try {                                                        
					if (sync == 1) {                                           
						if (be.getType() == Events.Select) {                     
							if (be.getSource().equals(yesbutton)) {   
								
								boolean b = true;
								for(BusiObject m:grid.getSelectionModel().getSelectedItems())
								{
									if(m.get("type").equals("-1"))
									{
										b=false;
										break;
									}
								}
								if(b)
								doposted(grid.getSelectionModel().getSelectedItems());
								else
								{
									MessageBox.alert("选择错误", "不允许选择已经使用过的商品。请重新选择。", null	);
								}
                                                                     
							}       
							else if (be.getSource().equals(button)) {   
								close();
								
                                
							}   
							else if(be.getSource() == reloadbutton)
							{
//								field.reset();
//								store.getStoreinfo().setSql(getsql());
//								store.reload();
								
								info.setSql(getsql());
								String groupfield = store.getGroupState();
								//store.removeAll();
								loder = null;
								loder = ss.getBaseLoaderX(type, info);
								store = new GroupingStore<BusiObject>(loder);
								store.groupBy(groupfield);
								grid.reconfigure(store,cm);
								loder.load();
							}
						}
						else if (be.getType() == Events.Hide) {    
							
						}
						else if (be.getType() == Events.Change) {              
							if (be.getSource().equals("")) {         
                                                                     
							}                                                      
						} else if (be.getType() == Events.KeyUp) {               
							if (be instanceof ComponentEvent) {                    
								if (((ComponentEvent) be).getKeyCode() == 13) // 回车
								{                                                    
								}                                                    
							}                                                      
						}                                                        
					}                                                          
				} finally {                                                  
					sync--;                                                    
				}                                                            
			}

		                                                       
                                                                     
		};                                                               
		return defaultlistener;                                          
	}    
	
}
